package com.maoye.ossp.biz.statement.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.maoye.ossp.biz.brand.entity.Supplier;
import com.maoye.ossp.biz.brand.service.ISupplierService;
import com.maoye.ossp.biz.contract.entity.AdvertAssbrands;
import com.maoye.ossp.biz.contract.entity.AdvertAssociated;
import com.maoye.ossp.biz.contract.entity.Assbrands;
import com.maoye.ossp.biz.contract.entity.AssociatedContract;
import com.maoye.ossp.biz.contract.entity.LeaseAssbrands;
import com.maoye.ossp.biz.contract.entity.LeaseAssociated;
import com.maoye.ossp.biz.contract.entity.MarketAssbrands;
import com.maoye.ossp.biz.contract.entity.MarketAssociated;
import com.maoye.ossp.biz.contract.entity.SelfAssbrands;
import com.maoye.ossp.biz.contract.entity.SelfAssociated;
import com.maoye.ossp.biz.contract.service.IAdvertAssociatedService;
import com.maoye.ossp.biz.contract.service.IContractService;
import com.maoye.ossp.biz.contract.service.ILeaseAssContractService;
import com.maoye.ossp.biz.contract.service.IMarketAssociatedService;
import com.maoye.ossp.biz.contract.service.ISelfAssociatedService;
import com.maoye.ossp.biz.statement.entity.BizStatementBillDetail;
import com.maoye.ossp.biz.statement.entity.BizStatementPaymentDetail;
import com.maoye.ossp.biz.statement.entity.BizStatementStmError;
import com.maoye.ossp.biz.statement.entity.BizStatementStmPrepaid;
import com.maoye.ossp.biz.statement.entity.StatementInvoice;
import com.maoye.ossp.biz.statement.entity.StatementOrderDetail;
import com.maoye.ossp.biz.statement.service.IBizStatementBillDetailService;
import com.maoye.ossp.biz.statement.service.IBizStatementPaymentDetailService;
import com.maoye.ossp.biz.statement.service.IBizStatementStmErrorService;
import com.maoye.ossp.biz.statement.service.IBizStatementStmPrepaidService;
import com.maoye.ossp.biz.statement.util.BizStatementConstant;
import com.maoye.ossp.biz.statement.util.excel.ExcelOperatorConstant;
import com.maoye.ossp.biz.statement.util.excel.JExcelOperator;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.entity.SysBaseFloor;
import com.maoye.ossp.sys.base.entity.SysBaseShop;
import com.maoye.ossp.sys.base.service.SysBaseFloorService;
import com.maoye.ossp.sys.base.service.SysBaseShopService;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.sc.api.domain.User;
import com.maoye.sc.service.user.UserServiceImpl;

/**
 * 结算对账单-自营经销(包括预付款账单) Controller
 * 
 * @author yangyf
 * 
 *         2014年2月17日
 */
@Controller
@RequestMapping(value = "/biz/statement/stm/prepaid/")
public class BizStatementStmPrepaidController extends BaseController {
	@Resource
	private IBizStatementStmPrepaidService stmPrepaidService;
	@Resource
	private IBizStatementStmErrorService stmErrorService;

	@Resource
	private IBizStatementPaymentDetailService paymentDetailService;
	
	@Resource
	private IBizStatementBillDetailService billDetailService;
	
	@Resource
	private SysBaseShopService sysBaseShopService ;
	
	@Resource
	private SysBaseFloorService sysBaseFloorService ;
	
	@Resource
	private ISupplierService supplierService;
	
	@Resource
	private UserServiceImpl userServiceImpl;
	
	@Resource
	private IContractService contractService;
	
	@Resource
	private IAdvertAssociatedService advertAssociatedService;
	
	@Resource
	private ILeaseAssContractService leaseAssContractService;
	
	@Resource
	private ISelfAssociatedService selfAssociatedService;
		
	@Resource
	private IMarketAssociatedService marketAssociatedService;
	
	/**
	 * 界面显示
	 * 
	 * @param stmPrepaid
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "list")
	public String list(BizStatementStmPrepaid stmPrepaid, Model model,
			HttpServletRequest request) {
		//获取登陆用户Id 
		Long userId=UserUtils.getCurrentUserId();
		//根据当前用户Id 如果是供应商 获取用户获取供应商信息
		Supplier supplier=supplierService.get(userId);
		QueryFilter queryFilter = getQuerFilter(request, stmPrepaid);//设置供应商编码
		String  isSupplier="0";
		if(supplier!=null){
			queryFilter.addFilter("supplierNo", supplier.getSupplierNo(), QueryOP.EQUAL);
		    isSupplier="1";
		 }
		Page<BizStatementStmPrepaid> page = (Page<BizStatementStmPrepaid>) stmPrepaidService
				.find(queryFilter);
		
		List<BizStatementStmPrepaid> list = page.getList();
		if (list != null) {
			for (BizStatementStmPrepaid prepaid : list) {
				if(prepaid!=null){
					// 联营合同
					if(prepaid.getContractType().equals("Z100")){
						Map map=contractService.getBrandByContractNo(prepaid.getContractNumber());
						if(map!=null){
						Assbrands brand=(Assbrands) map.get("brand");
						if(brand!=null){
						prepaid.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
						    prepaid.setCateName(brand.getCmcate().getCateName());
						   }
						 }
						}//自营合同
					}else if(prepaid.getContractType().equals("Z300")||prepaid.getContractType().equals("Z400")){
						Map map=selfAssociatedService.getBrandByContractNo(prepaid.getContractNumber());
						if(map!=null){
						SelfAssbrands brand=(SelfAssbrands) map.get("brand");
						if(brand!=null){
						prepaid.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
						    prepaid.setCateName(brand.getCmcate().getCateName());
						   }
						}
						}
					}else if(prepaid.getContractType().equals("Z200")){
						Map map=leaseAssContractService.getBrandByContract(prepaid.getContractNumber());
						if(map!=null){
						LeaseAssbrands brand=(LeaseAssbrands) map.get("brand");
						if(brand!=null){
						prepaid.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
						    prepaid.setCateName(brand.getCmcate().getCateName());
						   }
						}
						}
					}else if(prepaid.getContractType().equals("Z500")){
						Map map=advertAssociatedService.getBrandByContractNo(prepaid.getContractNumber());
						if(map!=null){
						AdvertAssbrands brand=(AdvertAssbrands) map.get("brand");
						if(brand!=null){
						prepaid.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
						    prepaid.setCateName(brand.getCmcate().getCateName());
						   }
						}
						}
					}else if(prepaid.getContractType().equals("Z600")){
						Map map=marketAssociatedService.getBrandByContractNo(prepaid.getContractNumber());
						if(map!=null){
						MarketAssbrands brand=(MarketAssbrands) map.get("brand");
						if(brand!=null){
						prepaid.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
						    prepaid.setCateName(brand.getCmcate().getCateName());
						   }
						 } 
						}
				}
			}
		}
	}
		page.setList(list);
		model.addAttribute("page", page);
		model.addAttribute("stmPrepaid", stmPrepaid);
		model.addAttribute("isSupplier",isSupplier);
		return resultPage("/biz/statement/prepaid/list", model, request);
 }

	/**
	 * 查看详细信息
	 * 
	 * @param id
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getPrepaidBillNo")
	public String getPrepaidBillNo(
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String id=request.getParameter("id");
        String billNo=request.getParameter("billNo");
        String companyCode=request.getParameter("companyCode");
        String year=request.getParameter("year");
       /* Long userId=UserUtils.getCurrentUserId();
        User user= userServiceImpl.getUserById(String.valueOf(userId));
		String flag="0";
		if(user!=null&& user.getUserType().equals("SUPPLIER")){
			 flag="1";
		}*/
		Map map=new HashMap();
		map.put("companyCode", companyCode);
		map.put("billNo",billNo);
		map.put("year",year);
		map.put("type","ZJ00");
		//根据billNo 获取扣款明细
		List<BizStatementPaymentDetail> paymentDetailList=paymentDetailService.getDetailList(map);
		//查看详细信息	
		BizStatementStmPrepaid stmPrepaid = stmPrepaidService.get(id);
		//设置本期实付款     
		stmPrepaid.setQuasiPayment(stmPrepaid.getAmountPaid()+stmPrepaid.getPrPeriodAccountopen());
		
		//根据billNo 获取采购/调价明细
		List<BizStatementBillDetail> billDetailList=billDetailService.getBizStatementBillDetailList(map);
		/*model.addAttribute("flag",flag);*/
		model.addAttribute("stmPrepaid", stmPrepaid);
		model.addAttribute("paymentDetailList",paymentDetailList);
		model.addAttribute("billDetailList",billDetailList);
		return "/biz/statement/prepaid/view";
	}
	
	@RequestMapping(value = "/print")
	public String print(
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String id=request.getParameter("id");
        String billNo=request.getParameter("billNo");
        String companyCode=request.getParameter("companyCode");
        String year=request.getParameter("year");
    	Map map=new HashMap();
		map.put("companyCode", companyCode);
		map.put("billNo",billNo);
		map.put("year",year);
		map.put("type","ZJ00");
		//根据billNo 获取扣款明细
		List<BizStatementPaymentDetail> paymentDetailList=paymentDetailService.getDetailList(map);
		//查看详细信息	
		BizStatementStmPrepaid stmPrepaid = stmPrepaidService.get(id);
		//设置本期实付款     
		stmPrepaid.setQuasiPayment(stmPrepaid.getAmountPaid()+stmPrepaid.getPrPeriodAccountopen());
		
		//根据billNo 获取采购/调价明细
		List<BizStatementBillDetail> billDetailList=billDetailService.getBizStatementBillDetailList(map);
		model.addAttribute("stmPrepaid", stmPrepaid);
		model.addAttribute("paymentDetailList",paymentDetailList);
		model.addAttribute("billDetailList",billDetailList);
		return "/biz/statement/prepaid/print";
	}
	
	/**
	 * 导出自营经数据和明细
	 * 
	 * @param billNo
	 *            参数
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "exportPrepaidAndDetail")
	public void exportPrepaidAndDetail(HttpServletRequest request, HttpServletResponse response) {
		String id=request.getParameter("id");
        String billNo=request.getParameter("billNo");
        String companyCode=request.getParameter("companyCode");
        String year=request.getParameter("year");
        Map map=new HashMap();
		map.put("companyCode", companyCode);
		map.put("billNo",billNo);
		map.put("year",year);
		map.put("type","ZJ00");
			//根据billNo 获取扣款明细
			List<BizStatementPaymentDetail> paymentDetailList=paymentDetailService.getDetailList(map);
			//查看详细信息
			BizStatementStmPrepaid stmPrepaid = stmPrepaidService.get(id);
			//根据billNo 获取采购/调价明细
			List<BizStatementBillDetail> billDetailList=billDetailService.getBizStatementBillDetailList(map);
			try {
				// 设置输出的格式
				response.reset();
				response.setContentType("application/vnd.ms-excel");
				// 获取浏览器类型
				String user_agent = request.getHeader("User-Agent").toLowerCase();
				String fileName = "";
				// 为不同的浏览器，对文件名进行不同的编码转换
				if (user_agent.indexOf("firefox") > 0) {
					fileName = new String("自营结算单明细".getBytes("UTF-8"), "iso8859-1");
				} else {
					fileName = URLEncoder.encode("自营结算单明细", "UTF-8");
				}
				response.setHeader("Content-disposition", "attachment; filename="
						+ fileName + ".xls");
				OutputStream os = response.getOutputStream();
				stmPrepaidService
						.exportPrepaidAndDetail(stmPrepaid,paymentDetailList,billDetailList,os);
				response.flushBuffer();
			} catch (IOException ex) {
				System.out.println("导出数据出错");
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
	}
	
	
	
	

	/**
	 * 导出自营经销结算对账单条数据
	 * 
	 * @param billNo
	 *            参数
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "{billNo}/exportPrepaid")
	public void exportPrepaid(@PathVariable String billNo,
			HttpServletRequest request, HttpServletResponse response) {
		List<BizStatementStmPrepaid> list = new ArrayList<BizStatementStmPrepaid>();
		BizStatementStmPrepaid stmPrepaid = stmPrepaidService
				.getPrepaidBill(billNo);

		list.add(stmPrepaid);
		JExcelOperator jExcelOperator = new JExcelOperator();

		// 导出到excel,并将导出文件发往客户端
		jExcelOperator.exportExcel(request, response,
				ExcelOperatorConstant.COLUMN_STATEMENTPREPAID,
				ExcelOperatorConstant.FIELD_STATEMENTPREPAID, list);
	}

	/**
	 * 扣款明细 显示
	 * 
	 * @param billNo
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "{type}/{billNo}/getPaymentBill")
	public String getPaymentBill(@PathVariable String type,
			@PathVariable String billNo, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		QueryFilter queryFilter = getQuerFilter(request, null);
		queryFilter.getParams().put("billNo", billNo);
		queryFilter.getParams().put("type", type);
		Page<BizStatementPaymentDetail> page = (Page<BizStatementPaymentDetail>) paymentDetailService
				.find(queryFilter);
		model.addAttribute("page", page);
		return "/biz/statement/counter/paymentDetailView";
	}

	/**
	 * 按条件查询 结算起始日期 供应商 是否确认结算
	 * 
	 * @param statementStmCounter
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "getByPrepaid")
	public String getByPrepaid(BizStatementStmPrepaid statementStmPrepaid,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Map map = new HashMap();
		map.put("isReconciliation", statementStmPrepaid.getIsReconciliation());
		map.put("startTime", statementStmPrepaid.getStartTime());
		map.put("endTime", statementStmPrepaid.getEndTime());
		map.put("supplierNo", statementStmPrepaid.getSupplierNo());
		List<BizStatementStmPrepaid> list = stmPrepaidService.PrepaidList(map);
		model.addAttribute("list", list);
		return "/biz/statement/counter/counterList";
	}

	/**
	 * 确认结算对账
	 * 
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "{id}/confirmPrepaid")
	public String confirmPrepaid(@PathVariable Long id,
			HttpServletRequest request, RedirectAttributes redirectAttributes,
			Model model) throws Exception {
		stmPrepaidService.confirmPrepaid(id);
		addMessage(redirectAttributes, "对账成功!");
		return "/biz/statement/prepaid/list";
	}

	/**
	 * 添加自营结算异常信息
	 * 
	 * @param statementStmError
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "{billNo}/add")
	public String add(@PathVariable String billNo,
			BizStatementStmError statementStmError, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		BizStatementStmPrepaid stmPrepaid = stmPrepaidService
				.getPrepaidBill(billNo);

		statementStmError.setIsConfirmed(BizStatementConstant.UN_CONFIRMED);
		statementStmError.setCreateTime(stmPrepaid.getStartTime());
		statementStmError.setDate(stmPrepaid.getEndTime());
		statementStmError.setSupplierName(stmPrepaid.getSupplierName());
		statementStmError.setErrorAmount(stmPrepaid.getAmountPaid());
		statementStmError.setActualAmount(stmPrepaid.getQuasiPayment());
		statementStmError
				.setStatementType(BizStatementConstant.STATEMENT_TYPE_2);

		model.addAttribute("stmCounter", stmPrepaid);

		model.addAttribute("statementStmError", statementStmError);

		return "/biz/statement/counter/counterErrorAdd";

	}

	/**
	 * 自营经销 供应商开票
	 * 
	 * @param model
	 * 
	 * @param id
	 *            参数
	 * @return 添加开票的页面
	 */
	@RequestMapping(value = "{id}/addInvoice")
	public String addInvoice(Model model, @PathVariable String id) {
		StatementInvoice invoice = new StatementInvoice();
		BizStatementStmPrepaid prepaid=null;
		if (StringUtils.isNotEmpty(id)) {
			 prepaid = stmPrepaidService.get(id);
			if (prepaid != null) {
				String counters=prepaid.getCounters();
				String []strArray=counters.split("\\.");
				String shopCode=null;
				String floorCode=null;
				if(strArray!=null&&strArray.length>0){
					Map map=new HashMap();
					shopCode=strArray[0];
					floorCode=strArray[2];
					map.put("code", shopCode);
					SysBaseShop shop=sysBaseShopService.getShopById(map);
					if(shop!=null){
						invoice.setRegionCode(shop.getRegionCode());
					}
					Map map1=new HashMap();
					map1.put("shopCode",shopCode);
					map1.put("code",floorCode);
					SysBaseFloor floor =sysBaseFloorService.getFloorById(map1);
					if(floor!=null){
						invoice.setFloorName(floor.getName());
					}
					invoice.setShopCode(shopCode);
					//设置楼层编码
					invoice.setDeptId(floorCode);
				}
				 String taxRate="";
				 String taxType="";
				 String taxRateCode="";
				if(prepaid.getContractType().equals("Z100")){
					Map map=contractService.getBrandByContractNo(prepaid.getContractNumber().substring(5));
					if(map!=null){
				    AssociatedContract associatedContract=(AssociatedContract) map.get("contract");
				    if(associatedContract!=null){
					taxRate=associatedContract.getTaxRate();
					taxRateCode=associatedContract.getTaxRateCode();
					taxType=associatedContract.getTaxType();
				    }
					}//自营合同
				}else if(prepaid.getContractType().equals("Z300")||prepaid.getContractType().equals("Z400")){
					Map map=selfAssociatedService.getBrandByContractNo(prepaid.getContractNumber().substring(5));
					if(map!=null){
						SelfAssociated selfAssociated=(SelfAssociated) map.get("contract");
						if(selfAssociated!=null){
						taxRate=selfAssociated.getTaxRate();
						taxRateCode=selfAssociated.getTaxRateCode();
						taxType=selfAssociated.getTaxType();
						}

					}
				}else if(prepaid.getContractType().equals("Z200")){
					Map map=leaseAssContractService.getBrandByContract(prepaid.getContractNumber().substring(5));
					if(map!=null){
						LeaseAssociated leaseAssociated=(LeaseAssociated) map.get("contract");
						if(leaseAssociated!=null){
						taxRate=leaseAssociated.getTaxRate();
						taxRateCode=leaseAssociated.getTaxRateCode();
						taxType=leaseAssociated.getTaxType();
						}

					}
				}else if(prepaid.getContractType().equals("Z500")){
					Map map=advertAssociatedService.getBrandByContractNo(prepaid.getContractNumber().substring(5));
					if(map!=null){
						AdvertAssociated advertAssociated=(AdvertAssociated) map.get("contract");
						if(advertAssociated!=null){
						taxRate=advertAssociated.getTaxRate();
						taxRateCode=advertAssociated.getTaxRateCode();
						taxType=advertAssociated.getTaxType();
						}

					}
				}else if(prepaid.getContractType().equals("Z600")){
					Map map=marketAssociatedService.getBrandByContractNo(prepaid.getContractNumber().substring(5));
					if(map!=null){
						MarketAssociated marketAssociated=(MarketAssociated) map.get("contract");
						if(marketAssociated!=null){
						taxRate=marketAssociated.getTaxRate();
						taxRateCode=marketAssociated.getTaxRateCode();
						taxType=marketAssociated.getTaxType();
						}

					}
			}
				if(taxRateCode.equals("R0")){
					invoice.setTaxRateCode("J0");
				}else if(taxRateCode.equals("R1")){
					invoice.setTaxRateCode("J1");
				}else if(taxRateCode.equals("R2")){
					invoice.setTaxRateCode("J4");
				}else if(taxRateCode.equals("R3")){
					invoice.setTaxRateCode("J5");
				}
				if(taxRate.equals("0")){
					invoice.setTaxRateName(taxRate+"%"+taxType);
					}else{
						invoice.setTaxRateName(taxRate+taxType);

					}
				if(taxRate.equals("17%")){
					invoice.setTaxRate(17.0);
				}else if(taxRate.equals("13%")){
					invoice.setTaxRate(13.0);
				}
				
				Double billingAmount = prepaid.getBillingAmount() == null ? 0.00
						: prepaid.getBillingAmount().doubleValue();
				invoice.setSupplierNo(prepaid.getSupplierNo());
				invoice.setSupplierName(prepaid.getSupplierName());
				invoice.setStartDate(prepaid.getStartTime());
				invoice.setEndDate(prepaid.getEndTime());
				invoice.setBillingAmount(billingAmount);
				invoice.setBillNo(prepaid.getBillNo());
				invoice.setPeriod(prepaid.getPeriod());
				invoice.setUnbilledAmount(billingAmount);
				invoice.setCompanyCode(prepaid.getCompanyCode());
				invoice.setYear(prepaid.getYear());
				invoice.setContractNumber(prepaid.getContractNumber());
				invoice.setInvoiceType(prepaid.getContractType());
				invoice.setBillId(Long.parseLong(id));
			}
		}
		if(prepaid!=null){
		   model.addAttribute("isReconciliation",prepaid.getIsReconciliation());
		}
		model.addAttribute("statementInvoice", invoice);
		String flag="0";//自营对账
		model.addAttribute("flag",flag);
		return "/biz/statement/invoice/supplies/add";
	}
}
